package com.sanpu.kxe.business.main.fragment;

import android.annotation.TargetApi;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.meiqia.meiqiasdk.util.MQUtils;
import com.sanpu.kxe.R;
import com.sanpu.kxe.base.BaseFragment;
import com.sanpu.kxe.business.main.adapter.HomeBannerViewHolder;
import com.sanpu.kxe.business.main.adapter.HomeCenterAdapter;
import com.sanpu.kxe.business.main.adapter.HomePageAdapter;
import com.sanpu.kxe.business.main.bean.HomeBannerOutput;
import com.sanpu.kxe.business.main.bean.HomeCenterOutput;
import com.sanpu.kxe.business.main.bean.HomePageOutput;
import com.sanpu.kxe.business.main.bean.InviteMakeMoneyOutput;
import com.sanpu.kxe.business.main.bean.NoticeOutput;
import com.sanpu.kxe.business.main.bean.RebateTotalOutput;
import com.sanpu.kxe.business.main.bean.UserConfigOutput;
import com.sanpu.kxe.business.main.contract.HomePageContract;
import com.sanpu.kxe.business.main.presenter.HomePagePresenter;
import com.sanpu.kxe.business.main.provider.MainOpenProvider;
import com.sanpu.kxe.business.main.view.MainActivity;
import com.sanpu.kxe.common.cache.CacheManage;
import com.sanpu.kxe.common.cache.CacheModel;
import com.sanpu.kxe.common.interfaces.CommonConfig;
import com.sanpu.kxe.common.view.NoScrollGridView;
import com.sanpu.kxe.module.banner.MZBannerView;
import com.sanpu.kxe.module.banner.holder.MZHolderCreator;
import com.sanpu.kxe.module.dialog.ShareEarningsDialog;
import com.sanpu.kxe.module.widget.MarqueeTextView;
import com.sanpu.kxe.module.widget.NumberRunningTextView;
import com.sanpu.kxe.module.widget.VerticalSwipeRefreshLayout;
import com.sanpu.kxe.utils.SystemBarHelper;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Description：首页
 * Created by 薛勇军 on 2018/7/9.
 */

public class HomePageFragment extends BaseFragment implements HomePageContract.View {

    @Bind(R.id.homePageGv)
    NoScrollGridView homePageGv;
    @Bind(R.id.banner)
    MZBannerView vMZBannerView;
    @Bind(R.id.tips)
    MarqueeTextView vTipsText;
    @Bind(R.id.recommendGv)
    NoScrollGridView recommendGv;
    @Bind(R.id.swipeRefreshLayout)
    VerticalSwipeRefreshLayout vSwipeRefreshLayout;

    @Bind(R.id.headerView)
    RelativeLayout headerView;
    @Bind(R.id.totalAmountTv)
    NumberRunningTextView totalAmountTv;
    @Bind(R.id.totalAmountPwdIv)
    ImageView totalAmountPwdIv;
    @Bind(R.id.dayAmountTv)
    TextView dayAmountTv;
    @Bind(R.id.showIv)
    ImageView showIv;

    private HomePageAdapter mHomeAdapter;

    private HomeCenterAdapter mCenterAdapter;

    private HomePageContract.Presenter mPresenter;

    private String thisMonthTotalAmount = "0";

    private ShareEarningsDialog vEarningsDialog;

    private boolean refreshInvite = false;

    private List<InviteMakeMoneyOutput> mInviteMakeMoneyOutputs = new ArrayList<>();

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisible()) {
            try {
                if (totalAmountTv != null)
                    totalAmountTv.setContent(thisMonthTotalAmount);
                if (mPresenter != null)
                    mPresenter.getRebateTotal();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected int getLayoutResID() {
        return R.layout.fragment_homepage;
    }

    @Override
    protected void initView() {
        super.initView();
        int barHeight = SystemBarHelper.getStatusBarHeight(getContext());
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) headerView.getLayoutParams();
        params.setMargins(0, barHeight, 0, 0);
        headerView.setLayoutParams(params);

        mHomeAdapter = new HomePageAdapter(getContext());
        homePageGv.setAdapter(mHomeAdapter);

        mCenterAdapter = new HomeCenterAdapter(getContext());
        recommendGv.setNumColumns(3);
        recommendGv.setAdapter(mCenterAdapter);
    }

    @Override
    protected void initData() {
        super.initData();
        boolean showTotal = CacheManage.getInstance().getCache(CacheModel.HOME_TOTAL_MONEY, false);
        if (!showTotal) {
            showIv.setImageResource(R.drawable.ic_home_head_show);
            totalAmountPwdIv.setVisibility(View.GONE);
            totalAmountTv.setVisibility(View.VISIBLE);
        } else {
            showIv.setImageResource(R.drawable.ic_home_head_close);
            totalAmountPwdIv.setVisibility(View.VISIBLE);
            totalAmountTv.setVisibility(View.GONE);
        }

        mPresenter = new HomePagePresenter(this);
        mPresenter.initUserData();
        mPresenter.initViewData();
        mPresenter.inviteMakeMoney();
        mPresenter.getRebateTotal();
    }

    @OnClick({R.id.marqueeMainRll, R.id.showIv, R.id.contactIv, R.id.shareIv})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.marqueeMainRll:
                UserConfigOutput mConfigOutput = CacheManage.getInstance().getCache(CacheModel.USER_CONFIG);
                if (mConfigOutput != null && !TextUtils.isEmpty(mConfigOutput.getMarqueeMainTextId())) {
                    NoticeOutput noticeOutput = new NoticeOutput();
                    noticeOutput.setId(mConfigOutput.getMarqueeMainTextId());
                    noticeOutput.setDetail(mConfigOutput.getMarqueeMainText());
                    MainOpenProvider.getInstance().openNoticeDetailsActivity(getContext(), noticeOutput, true);
                }
                break;
            case R.id.showIv:
                boolean showTotal = CacheManage.getInstance().getCache(CacheModel.HOME_TOTAL_MONEY, false);
                if (!showTotal) {
                    showIv.setImageResource(R.drawable.ic_home_head_close);
                    totalAmountPwdIv.setVisibility(View.VISIBLE);
                    totalAmountTv.setVisibility(View.GONE);
                } else {
                    showIv.setImageResource(R.drawable.ic_home_head_show);
                    totalAmountPwdIv.setVisibility(View.GONE);
                    totalAmountTv.setVisibility(View.VISIBLE);
                }
                CacheManage.getInstance().saveCache(CacheModel.HOME_TOTAL_MONEY, !showTotal);
                break;
            case R.id.contactIv:
                mPresenter.conversationWrapper();
                break;
            case R.id.shareIv:
                if (refreshInvite) {
                    refreshInvite = false;
                    vEarningsDialog = new ShareEarningsDialog(getContext(), mInviteMakeMoneyOutputs);
                } else {
                    if (vEarningsDialog == null) {
                        vEarningsDialog = new ShareEarningsDialog(getContext(), mInviteMakeMoneyOutputs);
                    } else {
                        vEarningsDialog.show();
                    }
                }
                break;
        }
    }

    @Override
    protected void setListener() {
        super.setListener();
        vSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mPresenter.getRebateTotal();
            }
        });
        recommendGv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                HomeCenterOutput output = ((HomeCenterAdapter) parent.getAdapter()).getItem(position);
                if (output != null) {
                    mPresenter.onHomeCenterItemClick(output);
                }
            }
        });
        homePageGv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                HomePageOutput output = ((HomePageAdapter) parent.getAdapter()).getItem(position);
                if (output != null) {
                    mPresenter.onHomePageItemClick(output);
                }
            }
        });
    }

    @Override
    public void showHomePageView(List<HomePageOutput> outputs) {
        if (outputs != null && outputs.size()>0) {
            homePageGv.setNumColumns(outputs.size());
            mHomeAdapter.setNotifyData(outputs);
            homePageGv.setVisibility(View.VISIBLE);
        } else {
            homePageGv.setVisibility(View.GONE);
        }
    }

    @Override
    public void showTipsView(String marqueeMainText) {
        if (!TextUtils.isEmpty(marqueeMainText)) {
            vTipsText.setText(marqueeMainText);
        }
    }

    @Override
    public void showInviteMakeMoneyData(List<InviteMakeMoneyOutput> inviteMakeMoneyOutputs) {
        if (inviteMakeMoneyOutputs != null) {
            refreshInvite = true;
            mInviteMakeMoneyOutputs.clear();
            mInviteMakeMoneyOutputs.addAll(inviteMakeMoneyOutputs);
        }
    }

    @Override
    public void showRebateTotalView(RebateTotalOutput output) {
        if (vSwipeRefreshLayout.isRefreshing()) {
            vSwipeRefreshLayout.setRefreshing(false);
        }
        if (output == null) {
            output = CacheManage.getInstance().getCache(CacheModel.REBATETOTAL);
        }
        if (output != null) {
            if (output.getWithdrawAmt() != null) {
                thisMonthTotalAmount = output.getAccRebAmt().toPlainString();
                totalAmountTv.setContent(thisMonthTotalAmount);
            }
            if (output.getDayRebAmt() != null) {
                dayAmountTv.setText("今日收益：" + output.getDayRebAmt().toPlainString() + "元");
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onConfigEvent(UserConfigOutput event) {
        if (event != null) {
            mPresenter.initUserData();
        }
    }

    @Override
    public void showBannerView(List<HomeBannerOutput> bannerOutputs) {
        if (bannerOutputs == null) {
            bannerOutputs = CacheManage.getInstance().getCache(CacheModel.BANNER);
        }
        if (bannerOutputs != null && !bannerOutputs.isEmpty()) {
            vMZBannerView.setVisibility(View.VISIBLE);
            vMZBannerView.setIndicatorHeight(11);
            vMZBannerView.setBannerPageClickListener(new MZBannerView.BannerPageClickListener() {
                @Override
                public void onPageClick(View view, int position) {
                    HomeBannerOutput bannerOutput =
                            (HomeBannerOutput) vMZBannerView.getAdapter().getItem(position);
                    mPresenter.onBannerItemClick(bannerOutput);
                }
            });
            vMZBannerView.setPages(bannerOutputs, new MZHolderCreator<HomeBannerViewHolder>() {
                @Override
                public HomeBannerViewHolder createViewHolder() {
                    return new HomeBannerViewHolder();
                }
            });
            if (bannerOutputs.size() > 1)
                vMZBannerView.start();
        } else {
            vMZBannerView.setVisibility(View.GONE);
        }
    }

    @Override
    public void showHomeCenterView(List<HomeCenterOutput> outputs) {
        if (outputs != null && outputs.size()>0) {
            mCenterAdapter.setNotifyData(outputs);
        }
    }

    @Override
    protected boolean hasBindEventBus() {
        return true;
    }

    @Override
    public void setPresenter(HomePageContract.Presenter presenter) {
        this.mPresenter = presenter;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mPresenter != null) {
            mPresenter.onDestroyPresenter();
            mPresenter = null;
        }
    }

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case CommonConfig.WRITE_EXTERNAL_STORAGE_REQUEST_CODE: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    mPresenter.conversationWrapper();
                } else {
                    MQUtils.show(getContext(), com.meiqia.meiqiasdk.R.string.mq_sdcard_no_permission);
                }
                break;
            }
        }

    }

    @Override
    public void showLoadingDialog(boolean cancelable) {
        ((MainActivity)getActivity()).showLoadingDialog(cancelable);
    }

    @Override
    public void showLoadingDialog(boolean cancelable, String content) {
        ((MainActivity)getActivity()).showLoadingDialog(cancelable, content);
    }

    @Override
    public void dismissLoadingDialog() {
        ((MainActivity)getActivity()).dismissLoadingDialog();
    }

    @Override
    public void showErrorText(Throwable e) {
        ((MainActivity)getActivity()).showErrorText(e);
    }
}
